import os
import json
import sys
from pathlib import Path


def get_config_path() -> Path:
    """获取应用配置目录路径"""
    # if os.name == 'nt':
    #     base = Path(os.environ['APPDATA'])
    # else:
    #     base = Path.home() / 'Library/Application Support'
    #
    # config_dir = base / 'WordFormatter'
    # config_dir.mkdir(parents=True, exist_ok=True)
    if getattr(sys, 'frozen', False):
        app_dir = Path(sys.executable).parent
    else:
        app_dir = Path(__file__).parent

    config_dir = app_dir / "config"  # ← 所有系统都用这个路径
    config_dir.mkdir(parents=True, exist_ok=True)
    return config_dir / "templates.json"


def load_json(file_path: Path) -> dict:
    """加载JSON文件"""
    try:
        if file_path.exists():
            with open(file_path, 'r', encoding='utf-8') as f:
                return json.load(f)
    except Exception as e:
        print(f"加载配置文件失败: {str(e)}")
    return {}


def save_json(data: dict, file_path: Path):
    try:
        with open(file_path, 'w', encoding='utf-8') as f:
            json.dump(data, f, ensure_ascii=False, indent=4)
    except Exception as e:
        error_msg = f"保存配置文件失败: {str(e)}"
        print(error_msg)
        raise RuntimeError(error_msg)